<template>
  <div class="course-list">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程名称、讲师或关键词..."
          size="large"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-bar">
        <div class="filter-group">
          <label>分类：</label>
          <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option 
              v-for="category in categories" 
              :key="category.value"
              :label="category.label" 
              :value="category.value" 
            />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>难度：</label>
          <el-select v-model="selectedLevel" placeholder="选择难度" @change="handleFilter">
            <el-option label="全部难度" value="" />
            <el-option label="入门" value="beginner" />
            <el-option label="初级" value="elementary" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>价格：</label>
          <el-select v-model="selectedPrice" placeholder="选择价格" @change="handleFilter">
            <el-option label="全部价格" value="" />
            <el-option label="免费" value="free" />
            <el-option label="付费" value="paid" />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>排序：</label>
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="最新发布" value="latest" />
            <el-option label="最受欢迎" value="popular" />
            <el-option label="评分最高" value="rating" />
            <el-option label="价格最低" value="price_low" />
            <el-option label="价格最高" value="price_high" />
          </el-select>
        </div>
        
        <div class="view-toggle">
          <el-button-group>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : ''"
              @click="viewMode = 'grid'"
            >
              <el-icon><Grid /></el-icon>
            </el-button>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : ''"
              @click="viewMode = 'list'"
            >
              <el-icon><List /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="courses-container">
      <div class="courses-header">
        <h2>{{ getCategoryTitle() }}</h2>
        <span class="course-count">共 {{ filteredCourses.length }} 门课程</span>
      </div>
      
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="courses-grid">
        <div 
          v-for="course in paginatedCourses" 
          :key="course.id"
          class="course-card"
          @click="viewCourse(course)"
        >
          <div class="course-image">
            <img :src="course.cover" :alt="course.title" />
            <div class="course-overlay">
              <el-button circle type="primary">
                <el-icon><VideoPlay /></el-icon>
              </el-button>
            </div>
            <div class="course-badges">
              <el-tag v-if="course.isFree" type="success" size="small">免费</el-tag>
              <el-tag v-if="course.isNew" type="warning" size="small">新课</el-tag>
              <el-tag v-if="course.isHot" type="danger" size="small">热门</el-tag>
            </div>
          </div>
          
          <div class="course-content">
            <div class="course-category">{{ course.category }}</div>
            <h3 class="course-title">{{ course.title }}</h3>
            <p class="course-desc">{{ course.description }}</p>
            
            <div class="course-meta">
              <div class="instructor">
                <el-avatar :size="24" :src="course.instructor.avatar">
                  {{ course.instructor.name.charAt(0) }}
                </el-avatar>
                <span>{{ course.instructor.name }}</span>
              </div>
              <div class="course-stats">
                <span class="rating">
                  <el-icon><Star /></el-icon>
                  {{ course.rating }}
                </span>
                <span class="students">{{ formatNumber(course.students) }}人</span>
              </div>
            </div>
            
            <div class="course-footer">
              <div class="course-price">
                <span v-if="course.isFree" class="free-price">免费</span>
                <template v-else>
                  <span v-if="course.originalPrice" class="original-price">¥{{ course.originalPrice }}</span>
                  <span class="current-price">¥{{ course.price }}</span>
                </template>
              </div>
              <div class="course-progress" v-if="course.progress !== undefined">
                <el-progress 
                  :percentage="course.progress" 
                  :show-text="false"
                  :stroke-width="4"
                />
                <span class="progress-text">{{ course.progress }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="courses-list">
        <div 
          v-for="course in paginatedCourses" 
          :key="course.id"
          class="course-item"
          @click="viewCourse(course)"
        >
          <div class="course-image">
            <img :src="course.cover" :alt="course.title" />
          </div>
          
          <div class="course-content">
            <div class="course-header">
              <div class="course-category">{{ course.category }}</div>
              <div class="course-badges">
                <el-tag v-if="course.isFree" type="success" size="small">免费</el-tag>
                <el-tag v-if="course.isNew" type="warning" size="small">新课</el-tag>
                <el-tag v-if="course.isHot" type="danger" size="small">热门</el-tag>
              </div>
            </div>
            
            <h3 class="course-title">{{ course.title }}</h3>
            <p class="course-desc">{{ course.description }}</p>
            
            <div class="course-meta">
              <div class="instructor">
                <el-avatar :size="28" :src="course.instructor.avatar">
                  {{ course.instructor.name.charAt(0) }}
                </el-avatar>
                <span>{{ course.instructor.name }}</span>
              </div>
              <div class="course-stats">
                <span class="rating">
                  <el-icon><Star /></el-icon>
                  {{ course.rating }}
                </span>
                <span class="students">{{ formatNumber(course.students) }}人学习</span>
                <span class="duration">{{ course.duration }}</span>
              </div>
            </div>
          </div>
          
          <div class="course-actions">
            <div class="course-price">
              <span v-if="course.isFree" class="free-price">免费</span>
              <template v-else>
                <span v-if="course.originalPrice" class="original-price">¥{{ course.originalPrice }}</span>
                <span class="current-price">¥{{ course.price }}</span>
              </template>
            </div>
            
            <div class="course-progress" v-if="course.progress !== undefined">
              <el-progress 
                :percentage="course.progress" 
                :show-text="false"
                :stroke-width="6"
              />
              <span class="progress-text">{{ course.progress }}% 完成</span>
            </div>
            
            <el-button type="primary" @click.stop="enrollCourse(course)">
              {{ course.progress !== undefined ? '继续学习' : '立即学习' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="filteredCourses.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Grid, List, VideoPlay, Star
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedLevel = ref('')
const selectedPrice = ref('')
const sortBy = ref('latest')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(12)

// 分类数据
const categories = ref([
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '移动开发', value: 'mobile' },
  { label: '数据科学', value: 'data' },
  { label: '人工智能', value: 'ai' },
  { label: '云计算', value: 'cloud' },
  { label: '网络安全', value: 'security' },
  { label: '产品设计', value: 'design' }
])

// 课程数据
const courses = ref([
  {
    id: 1,
    title: 'Vue3 + TypeScript 实战开发',
    description: '从零开始学习Vue3和TypeScript，构建现代化前端应用',
    cover: '/images/course-vue3.jpg',
    category: '前端开发',
    level: 'intermediate',
    instructor: {
      name: '张老师',
      avatar: '/images/instructor-1.jpg'
    },
    students: 12500,
    rating: 4.8,
    duration: '20小时',
    price: 299,
    originalPrice: 399,
    isFree: false,
    isNew: true,
    isHot: true,
    progress: 65
  },
  {
    id: 2,
    title: 'React 18 新特性详解',
    description: '深入理解React 18的并发特性和Hooks最佳实践',
    cover: '/images/course-react.jpg',
    category: '前端开发',
    level: 'advanced',
    instructor: {
      name: '李老师',
      avatar: '/images/instructor-2.jpg'
    },
    students: 8900,
    rating: 4.7,
    duration: '15小时',
    price: 199,
    isFree: false,
    isNew: false,
    isHot: true,
    progress: 30
  },
  {
    id: 3,
    title: 'JavaScript 基础入门',
    description: '零基础学习JavaScript编程语言',
    cover: '/images/course-js.jpg',
    category: '前端开发',
    level: 'beginner',
    instructor: {
      name: '王老师',
      avatar: '/images/instructor-3.jpg'
    },
    students: 25600,
    rating: 4.9,
    duration: '30小时',
    price: 0,
    isFree: true,
    isNew: false,
    isHot: true
  },
  {
    id: 4,
    title: 'Node.js 后端开发实战',
    description: '使用Node.js构建高性能的后端API服务',
    cover: '/images/course-nodejs.jpg',
    category: '后端开发',
    level: 'intermediate',
    instructor: {
      name: '赵老师',
      avatar: '/images/instructor-4.jpg'
    },
    students: 6700,
    rating: 4.6,
    duration: '25小时',
    price: 399,
    originalPrice: 499,
    isFree: false,
    isNew: true,
    isHot: false
  }
  // 更多课程数据...
])

// 计算属性
const filteredCourses = computed(() => {
  let filtered = courses.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(course => 
      course.title.toLowerCase().includes(keyword) ||
      course.description.toLowerCase().includes(keyword) ||
      course.instructor.name.toLowerCase().includes(keyword) ||
      course.category.toLowerCase().includes(keyword)
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(course => course.category === selectedCategory.value)
  }

  // 难度筛选
  if (selectedLevel.value) {
    filtered = filtered.filter(course => course.level === selectedLevel.value)
  }

  // 价格筛选
  if (selectedPrice.value) {
    if (selectedPrice.value === 'free') {
      filtered = filtered.filter(course => course.isFree)
    } else if (selectedPrice.value === 'paid') {
      filtered = filtered.filter(course => !course.isFree)
    }
  }

  // 排序
  switch (sortBy.value) {
    case 'popular':
      filtered.sort((a, b) => b.students - a.students)
      break
    case 'rating':
      filtered.sort((a, b) => b.rating - a.rating)
      break
    case 'price_low':
      filtered.sort((a, b) => a.price - b.price)
      break
    case 'price_high':
      filtered.sort((a, b) => b.price - a.price)
      break
    default: // latest
      filtered.sort((a, b) => b.id - a.id)
  }

  return filtered
})

const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCourses.value.slice(start, end)
})

// 方法
const getCategoryTitle = () => {
  if (selectedCategory.value) {
    const category = categories.value.find(c => c.value === selectedCategory.value)
    return category ? category.label : '课程列表'
  }
  return '全部课程'
}

const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewCourse = (course) => {
  router.push(`/classroom/course/${course.id}`)
}

const enrollCourse = (course) => {
  if (course.progress !== undefined) {
    // 继续学习
    router.push(`/classroom/course/${course.id}/learn`)
  } else {
    // 立即学习
    ElMessage.success(`开始学习：${course.title}`)
    router.push(`/classroom/course/${course.id}`)
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.course-list {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.search-filter-section {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
}

.search-bar {
  margin-bottom: 20px;
  
  .el-input {
    max-width: 600px;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  
  label {
    font-size: 14px;
    color: var(--el-text-color-regular);
    white-space: nowrap;
  }
  
  .el-select {
    width: 140px;
  }
}

.view-toggle {
  margin-left: auto;
  
  @media (max-width: 768px) {
    margin-left: 0;
  }
}

.courses-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.courses-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .course-count {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.course-card {
  border: 1px solid var(--el-border-color-extra-light);
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    border-color: var(--el-color-primary);
  }
}

.course-image {
  position: relative;
  height: 180px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .course-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:hover .course-overlay {
    opacity: 1;
  }
  
  .course-badges {
    position: absolute;
    top: 12px;
    left: 12px;
    display: flex;
    gap: 6px;
  }
}

.course-content {
  padding: 20px;
}

.course-category {
  font-size: 12px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  margin-bottom: 12px;
}

.course-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
  @include text-ellipsis(2);
}

.course-desc {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  @include text-ellipsis(2);
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.instructor {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.course-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  
  .rating {
    display: flex;
    align-items: center;
    gap: 2px;
    
    .el-icon {
      color: #ffd700;
    }
  }
}

.course-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-price {
  .free-price {
    color: var(--el-color-success);
    font-weight: 600;
  }
  
  .original-price {
    text-decoration: line-through;
    color: var(--el-text-color-placeholder);
    font-size: 12px;
    margin-right: 8px;
  }
  
  .current-price {
    color: var(--el-color-danger);
    font-weight: 600;
    font-size: 16px;
  }
}

.course-progress {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .el-progress {
    width: 80px;
  }
  
  .progress-text {
    font-size: 12px;
    color: var(--el-color-primary);
    font-weight: 500;
  }
}

.courses-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 32px;
}

.course-item {
  display: flex;
  gap: 20px;
  padding: 20px;
  border: 1px solid var(--el-border-color-extra-light);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
  
  .course-image {
    width: 200px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .course-content {
    flex: 1;
    padding: 0;
  }
  
  .course-actions {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-end;
    gap: 12px;
    flex-shrink: 0;
  }
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

@media (max-width: 768px) {
  .courses-grid {
    grid-template-columns: 1fr;
  }
  
  .course-item {
    flex-direction: column;
    
    .course-image {
      width: 100%;
      height: 160px;
    }
    
    .course-actions {
      flex-direction: row;
      align-items: center;
    }
  }
}
</style>
